from user.models import User
import jwt
from rest_framework_jwt.authentication import jwt_decode_handler


def check_token(request):
    """
    专用于验证token的函数 需要时在其他views文件中引入
    :param request : 前端传回的request
    :return : response{'code':'int', 'msg':''} 其中code<0时验证失败 调用的函数可以直接返回response
    """
    jwt_token = request.META.get('HTTP_AUTHORIZATION', None)
    token = jwt_token
    if token is None:
        return None
    try:
        payload = jwt_decode_handler(token)
    except jwt.ExpiredSignature:
        response = {
            'msg': 'token已过期,请重新登录',
            'code': -1
        }
        return response
    except:
        response = {
            'msg': '非法用户',
            'code': -2
        }
        return response
    user_id = payload.get('user_id')
    if User.objects.filter(id=user_id).count() == 0:
        response = {
            'msg': '非法用户',
            'code': -2
        }
        return response
    user = User.objects.get(id=user_id)
    # if not user.is_administrator:
    #     response = {
    #         'msg': '无此权限',
    #         'status': 403
    #     }
    #     return response
    response = {
        'user': user.username,
        'msg': 'ok',
        'code': 0
    }
    return response
